package com.china08.yxyapi.api.home.activity.healthcompetition.huodongtongji;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionStudent;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;

/**
 * 健康知识竞赛 该学校各学段总参与人数 参与率 平均分
 * 
 * @author zd.Jin
 *
 *
 */
@CrossOrigin
@RestController
public class HealthCompetionTongjiByStageController extends YxyApiBaseController {
	@Value("${yx.rest.api.yx.path}")
	private String yxpath;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private MongoTemplate mongoTemplate;

	@RequestMapping(value = "/api_yw/home/activity/healthcompetition/huodongtongji/stagetongji", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public List<RespModel> process(HttpServletRequest request, HttpServletResponse response,
			@RequestBody ReqModel reqModel) {
		List<RespModel> list = new ArrayList<>();
		DecimalFormat df = new DecimalFormat("######0.00");
		// 计算各学段参与学生平均分
		TypedAggregation<YxyCompetitionStudent> totalavg = Aggregation.newAggregation(YxyCompetitionStudent.class,
				Aggregation.match(Criteria.where("status").is(2).and("schoolId").is(reqModel.schoolId)),
				Aggregation.group("stage").avg("score").as("avg").count().as("total").first("stage").as("stage"));
		AggregationResults<RespModel> resultZongtotal = mongoTemplate.aggregate(totalavg, RespModel.class);
		list = resultZongtotal.getMappedResults();
		for (RespModel res : list) {
			try {
				HttpHeaders headers = new HttpHeaders();
				MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
				headers.setContentType(type);
				headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
				Map<String, Object> formMap = new HashMap<String, Object>();
				formMap.put("stage", res.stage);
				formMap.put("schoolId", reqModel.schoolId);
				HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
				SchRespModel httpResult = restTemplate.postForObject(yxpath + "/comm/stucount/schandstage", formEntity,
						SchRespModel.class);
				Integer studentcount = httpResult.stucount;
				Double rate = 0.0d;
				if (studentcount != 0) {
					Double aLong = (double) res.total / studentcount;
					rate = Double.valueOf(df.format(aLong * 100));
				}
				res.rate = rate;
				res.avg = Double.valueOf(df.format(res.avg));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	// 远程调用接口,查询学校下小学初中高中共有多少学生
	protected static class SchRespModel extends YxyApiReqModel {
		// 学生总数
		public Integer stucount;
	}

	protected static class ReqModel extends YxyApiReqModel {
		// 学校id
		public String schoolId;
	}

	protected static class RespModel extends YxyApiRespModel {
		// 学段
		public String stage;
		// 总参与人数
		public Integer total;
		// 参与率
		public Double rate;
		// 平均分
		public Double avg;
	}
}
